import React from 'react';

import $ from 'jquery';

import {
    Link
} from 'react-router';

class TreeMenu extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data:this.props.data
        };
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.data !== nextProps.data) {
            this.setState({
                data:nextProps.data
            });
        }
    }

    itemClickHandler = (e)=>{
        let obj = $(e.currentTarget);
        let id = obj.prop('id');
        if (obj.hasClass('tree_active')) {
            obj.removeClass('tree_active');
            $('#child_'+id).slideUp(300);
            obj.find('span').removeClass('tree_icon_down');
        } else {
            obj.addClass('tree_active');
            $('#child_'+id).slideDown(300);
            obj.find('span').addClass('tree_icon_down');
        }
    };

    render() {
        return (
            <div className="tree_menu">
                {this.state.data.map((item)=>{
                    return (
                        <div className="am-panel tree_main">
                            <div id={item.menu_id} className="am-panel-hd tree_main_item" onClick={this.itemClickHandler}>
                                {item.menu_text}
                                <span className="am-icon-chevron-left am-icon-fw am-fr tree_icon_trm"/>
                            </div>
                            <div id={'child_'+item.menu_id} className="am-panel-bd tree_panel" style={{display:'none'}}>
                                <ul className="tree_list">
                                    {item.sub_menus && item.sub_menus.map((child)=>{
                                        return (
                                            <li><Link to={child.menu_link} activeClassName="tree_item_active">{child.menu_text}</Link></li>
                                        );
                                    })}
                                </ul>
                            </div>
                        </div>
                    )
                })}
            </div>
        );
    }
}

export default TreeMenu;